import React from 'react'
// ===================================================================== Temp
import SubmitForm from '#cpt/temp/SubmitForm'
import Table from '#cpt/temp/Table'
import Controls from '#cpt/temp/Controls'
import Confirm from '#cpt/temp/Confirm'
import TableControls from '#cpt/temp/TableControls'
import Cols from '#private/cols'
// ===================================================================== global declare
const { $fn, $http, $Lazy } = window
// ===================================================================== $Lazy
const Select 		= $Lazy.load(()=>import('@antd/form/select'))
const Page 			= $Lazy.load(()=>import('#tp/page/page-container-scroll'))
const Box 			= $Lazy.load(()=>import('#tp/box/box'))
// 
const message 		= $Lazy.file(()=>import('@antd/message'))
const confirm 		= $Lazy.file(()=>import('@antd/confirm'))
const $cache 		= $Lazy.file(()=>import('#private/cache-api'))
// 
const BatchCode 	= $Lazy.state(()=>import('./cpt/batch-code-table'))
const AddDicModal 	= $Lazy.state(()=>import('./cpt/add-dic-modal'))
// ===================================================================== 
const proStatus = [ { name: "已审核", value: "1" },{ name: "待审核", value: "0" },{ name: "待保存", value: "-2" }]
// ===================================================================== component
class Index extends React.Component{
	state = {
		data:[],
		specData:{},	// 当前条码信息
		to_codes: [],	// 表格的批量条码
		// 搜索表单列表
		formData: [
			{ label: '条码号',			name: 'spec_code',  required:true,	full:true,	itemClassName:'spec_code',	autoFocus:true,  type:'textarea',
				btn:{ label:'生成', onClick:value=>{
					value && this.generateSpec(value)
				} }
			},
			{ label: '选择项目',			name: 'project_id',  	full:true, 	type: 'select-table',	loading:true, disabled: true, cols:Cols['specimenkindSelect'], isKeydown: 'kind',	onValue:({value})=>{this.addProject(value)}},
		],
		specType:[]
	}
		
	componentDidMount(){
		this.getSelect()
		const { spec_codes } = $fn.query()
		const spec_code = spec_codes?.split(',').join('\r')
		setTimeout(() => {
			this.formRef.setValue({spec_code: spec_code})
			spec_code && this.generateSpec(spec_code)
		}, 500);
	}

	// 项目明细
	cols=[
		{ title: '项目代码', 	dataIndex: 'kind_code',				...$fn.table.exp_num,	 },
		{ title: '项目名称', 	dataIndex: 'kind_name', 			width:150 },
		{ title: '项目属性 ', 	dataIndex: 'kind_type_name',  		width:120,  },
		{ title: '项目类别 ', 	dataIndex: 'category_name',  		width:120,  },
		{ title: '子项目 ', 		dataIndex: 'child_kind_name',  		width:150,  },
		{ title: '岗位 ', 		dataIndex: 'project_name',  		width:120,  },
		{ title: '项目状态 ', 	dataIndex: 'enabled',  				width:100,	render: text => $fn.getState(proStatus,text)  },
		{ title: '标本类型 ', 	dataIndex: 'spec_type_name', 		width:150,	name:'spec_type', 	render: (text, {uuid}) => {
			const {specType} = this.state
			return <Select
				name		= 'spec_type'
				value		= {text}  
				data		= {specType}
				width		= '100%' 
				onChange 	= { value  =>{
					confirm.then(f=>{
						value && $http.submit(null,'specimen-kind/savespectype',{ param:{spec_type:specType[value].code,uuid}, loadingText:`添加中`}).then(data=>{
							message.then(f=>f.success(`操作成功`))
							this.getProjectList()
						})
					})
				}}
			/>
		}},
		TableControls.controls.call(this,{ width: 150 })
	]	
	// 表格操作按钮
	table_controls = ({uuid,spec_id,enabled}) => {
		const to_spec_ids = this.batchTableRef.state.data.map(v => v.uuid)
		return [
			TableControls.click.call(this, '添加', ()=>{
				this.addDicModal.open()
			}),
			+enabled !== 1?Confirm.call(this, '删除', 'specimen-kind/del',{
				query:{kind_id: uuid, spec_id: [spec_id], to_spec_ids},
				onOk:()=> this.getProjectList()
			}):null,	// 删除
		]
	}	
	
	// 操作按钮
	controls = () => {
		return [
			Controls.back.call(this,{refresh:true, code: 'F1'} ),	// 返回
			Controls.submit.call(this, '保存', 'specimen-kind/savekind', { param: () => {
				const to_codes = this.batchTableRef.state.data.map(v => v.spec_code)
				return {spec_id: this.state.specData.uuid, to_codes, additional_kind: 1}
			}, onOk: () => this.getProjectList(), code: 'F8'} ),
			Controls.submit.call(this, '保存并审核', 'specimen/saveandaudit', { param: () => {
				const { uuid } = this.state.specData
				const to_codes = this.batchTableRef.state.data.map(v => v.spec_code)
				return {spec_id: uuid, ...this.state.specData, status: 1, additional_kind: 1, to_codes}
			}, onOk: () => this.getProjectList()}),
		]
	}

	// 生成
	generateSpec = (value)=> {
		this.getSpec(value)
		$http.submit(null,'specimen/checkenter',{ param:{ spec_codes: this.spec_codes }}).then(({info, res})=>{
			if($fn.hasObject(info)){
				$fn.disabledRows(this.state.formData, 'project_id', false)
				this.setState({specData:info})
				this.batchTableRef.setState({data:res})
				this.getProjectList()
			}
		}).catch(()=>{
			const specData = {}
			this.setState({specData})
		})
	}
	
	// 解析条码
	getSpec = (data) => {
		let spec_codes = data
		spec_codes = spec_codes.match(/\d{14}|\d{12}/g)
		this.spec_codes = Array.from(new Set(spec_codes)).join(',')
	}
	
	// 添加项目
	addProject = value => {
		const {uuid,spec_code} = this.state.specData
		$http.submit(null,'specimen-kind/batchadd',{ param:{ kind_ids:[value], spec_id:uuid,spec_code}, loadingText:`添加中`}).then(data=>{
			message.then(f=>f.success(`添加成功`))
			this.getProjectList()
			this.formRef.reset(['project_id'])
		}).catch(() => {
			// 清空 选择项目
			this.formRef.reset(['project_id'])
		})
	}
	
	// 刷新列表
	getProjectList = () => {
		const { uuid: spec_id, spec_code } = this.state.specData
		$http.pull(this,'specimen-kind/index', { param: {spec_id, spec_code, additional_kind: 1} })
	}
	
	// 获取下拉数据
	getSelect = () => {
		const { formData } = this.state
		$cache.then( async f => {
			// 选择项目
			$fn.setRow( formData, 'project_id', await f.getCache({ api:'specimenkindSelect' }) )
			// 标本类型
			const specType = $fn.setRow( this.cols, 'spec_type', await f.getDicCache({ code: 2000, refresh:true }) )
			
			this.setState({ formData, specType })
		})
	}
	
	// 刷新字典
	refreshDic = () => {
		const { formData } = this.state
		$cache.then( async f => {
			// 标本类型
			const specType = $fn.setRow( this.cols, 'spec_type', await f.getDicCache({ code: 2000, refresh:true }) )
			
			this.setState({ formData, specType })
		})
	}
	
	render() {
		return (
			<>
				<Page title='批量加做项目' controls={this.controls()} style={{minHeight: '100%'}} >,
					<section className='ex fx pt10 bcf'>
						{/* 表单 */}
						<div className=' ex fv pr10'>
							{ SubmitForm.call(this,{ labelWidth:'s7',})}
						</div>
					</section>
					{/* 批量条码表格 */}
					<BatchCode onRef={ ref => this.batchTableRef = ref } />
					{/* 项目明细表格 */}
					<Box title="项目明细" className='mt5' style={{minHeight:350}} flex contentClassName='rel fv pt10'>
						{ Table.call(this, { wrapClassName: 'xmlr' }) }
					</Box>
				</Page>
				{/* 添加字典 */}
				<AddDicModal onRef = { ref => this.addDicModal = ref } onRefresh = {this.refreshDic} />
			</>
		)
	}
}

export default Index